﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;

public partial class Delivery_Invoice : INTPage
{
    SqlHelp help = new SqlHelp();
    InvoiceModel model = new InvoiceModel();
    InvoiceDAO comm = new InvoiceDAO();
    CommonMethod comHelp = new CommonMethod();
      
    protected void Page_Load(object sender, EventArgs e)
    {
        CommonMethod.IsTimeOutUserCode(this, CommonModel.errorTimeOutUrl1);
        if (!IsPostBack)
        { bindInti(Session["UserCode"].ToString()); }
        //OpenFileDialog ofd = new OpenFileDialog();            
        ////过滤文件类型            
        //ofd.Filter = "文本文件(*.txt)|*.txt|日志文件(*.log)|*.log";           
        ////显示名称            
        //ofd.Title = "选择待分析日志文件";            
        //ofd.InitialDirectory = Application.StartupPath;           
        ////设置为可多选文件            
        //ofd.Multiselect=true;            
        ////设置打开对话框的默认位置            
        //ofd.InitialDirectory = @"C:\Documents and Settings\Administrator\Application Data\SE_logs";
        FileUpload1.Attributes.Add("Filter", "文本文件(*.txt)|*.txt|日志文件(*.log)|*.log");
    }

    protected void cmdAdd_Click(object sender, EventArgs e)
    {
        CommonMethod.IsTimeOutUserCodeAndCoCode(this, CommonModel.errorTimeOutUrl1);
        
        model.UserCode = Session["UserCode"].ToString();
        model.SoNo = (ddlType.SelectedValue.Equals("1")) ? ddlSoNo.SelectedValue : "";
        model.InvoiceNo = txtInvoiceNo.Text;
        model.InvoiceDate = txtDate.Value;
        model.InvoiceAmount = txtInvoicAmount.Value;
        model.ContractNoMain = ddlContractNo.SelectedValue;
        model.CoCode = Session["CoCode"].ToString();
        model.InvoiceDesc = TxtDesc.Text;
        model.InvoiceContractAmount = txtAmount.Value;
        model.InvoiceType = Convert.ToInt16(ddlType.SelectedValue.ToString());
        model.ExpressDeliveryNo = txtExpressDeliveryNo.Text;
        model.DespatchDate = txtDespatchDate.Value;
        model.txtSignInDate = txtSignInDate.Value;

        if (comm.InvoiceAdd(model) > 0)
        {
            CommonMethod.regAlertMessage(updHead, "success！", this);
            InvoiceContractBind(txtInvoiceNo.Text);
            double leftHead = Convert.ToDouble(txtLeftAmount.Value);
            double amount = Convert.ToDouble(txtAmount.Value);
            double contactAmount = Convert.ToDouble(txtContractLeftAmount.Value);
            if (leftHead > 0 && leftHead >= amount)
            {
                txtLeftAmount.Value = (leftHead - amount).ToString();
            }
            txtContractLeftAmount.Value = (contactAmount - amount).ToString();
        }
        else
        {
            CommonMethod.regAlertMessage(updHead, "failed！", this);
        }
        HeadSet();
    }
    protected void cmdEdit_Click1(object sender, EventArgs e)
    {
        model.M_InvoiceContractID = Convert.ToInt64(hiddEdit.Value);
        model.UserCode = Session["UserCode"].ToString();
        model.SoNo = (ddlType.SelectedValue.Equals("1")) ? ddlSoNo.SelectedValue : "";
        model.ContractNoMain = ddlContractNo.SelectedValue;
        model.InvoiceContractAmount = txtAmount.Value;
        model.InvoiceType = Convert.ToInt16(ddlType.SelectedValue.ToString());
        if (comm.InvoiceUpdate(model) > 0)
        {
            CommonMethod.regAlertMessage(updHead, "success！", this);
            cmdAdd.Enabled = true;
            cmdEdit.Enabled = false;
            hiddEdit.Value = "0";
            GetTradingBillingAmount(ddlContractNo.SelectedValue.ToString(), ddlType.SelectedValue.Equals("1") ? (string.IsNullOrEmpty(ddlSoNo.SelectedValue) ? "" : ddlSoNo.SelectedValue.ToString()) : "");
        }
        else
        {
            CommonMethod.regAlertMessage(updHead, "failed！", this);
        }
        CommonMethod.regAlertMessageScript(updHead, "boundvalid();", this);
    }
    protected void cmdDelete_Click(object sender, EventArgs e)
    {
        if (comm.InvoiceDelete(txtInvoiceNo.Text) > 0)
        {
            Response.Redirect("InvoiceList.aspx");
        }
        else
        {
            CommonMethod.regAlertMessage(updHead, "failed！", this);
        }
    }

    protected void ddlContractNo_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlType.SelectedValue.Equals("1"))
        {
            SoNoBind(ddlContractNo.SelectedValue);
        }
        else
        {
            ddlSoNo.Enabled = false;
            ddlSoNo.Items.Clear();
        }
        GetTradingBillingAmount(ddlContractNo.SelectedValue.ToString(), ddlType.SelectedValue.Equals("1") ? (string.IsNullOrEmpty(ddlSoNo.SelectedValue) ? "" : ddlSoNo.SelectedValue.ToString()) : "");
        CommonMethod.regAlertMessageScript(updHead, "boundvalid();", this);
    }
    protected void ddlType_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlType.SelectedValue.ToString().Equals("1"))
        {
            ddlSoNo.Enabled = true;
            SoNoBind(ddlContractNo.SelectedValue);
        }
        else
        {
            ddlSoNo.Enabled = false;
            ddlSoNo.Items.Clear();
        }
        GetTradingBillingAmount(ddlContractNo.SelectedValue.ToString(), ddlType.SelectedValue.Equals("1") ? (string.IsNullOrEmpty(ddlSoNo.SelectedValue) ? "" : ddlSoNo.SelectedValue.ToString()) : "");
        
        CommonMethod.regAlertMessageScript(updHead, "boundvalid();", this);
    }
    protected void ddlSoNo_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            GetTradingBillingAmount(ddlContractNo.SelectedValue.ToString(), ddlSoNo.SelectedValue.ToString());
        }
        catch { }
    }
    protected void GrvColumns_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        if (comm.InvoiceContractDelete(Convert.ToInt16(Grv.DataKeys[e.RowIndex]["M_InvoiceContractID"].ToString())) > 0)
        {
            CommonMethod.regAlertMessage(updHead, "success", this);
            InvoiceContractBind(txtInvoiceNo.Text);
            HeadSet();
        }
        else
        {
            CommonMethod.regAlertMessage(updHead, "failed", this);
        }
        CommonMethod.regAlertMessageScript(updHead, "boundvalid();", this);
    }
    protected void Grv_RowEditing(object sender, GridViewEditEventArgs e)
    {
        
    }
    protected void Grv_SelectedIndexChanged(object sender, EventArgs e)
    {
        string strID = Grv.SelectedDataKey["M_InvoiceContractID"].ToString();

        DataTable dt = comm.GetDetail(strID);
        if (dt != null && dt.Rows.Count > 0)
        {
            hiddEdit.Value = strID;
            ddlType.Enabled = false;

            ddlType.SelectedValue = dt.Rows[0]["InvoiceType"].ToString();
            txtAmount.Value = dt.Rows[0]["InvoiceContractAmount"].ToString();
            ddlContractNo.Items.Add(new ListItem(dt.Rows[0]["ContractNoMain"].ToString(), dt.Rows[0]["ContractNoMain"].ToString()));
            ddlSoNo.Items.Add(new ListItem(dt.Rows[0]["SONo"].ToString(), dt.Rows[0]["SONo"].ToString()));

            GetTradingBillingAmount(ddlContractNo.SelectedValue.ToString(), ddlType.SelectedValue.Equals("1") ? (string.IsNullOrEmpty(ddlSoNo.SelectedValue) ? "" : ddlSoNo.SelectedValue.ToString()) : "");

            try
            {
                double a = Convert.ToDouble(txtContractLeftAmount.Value);
                double b = Convert.ToDouble(txtAmount.Value);
                txtContractLeftAmount.Value = (a + b).ToString();
            }
            catch { }
            cmdAdd.Enabled = false;
            cmdEdit.Enabled = true;
            CommonMethod.regAlertMessageScript(updHead, "boundvalid();", this);
        }
    }

    #region Method

    private void bindInti(string userCode)
    {
        comHelp.GetRight(this, new string[] { Session["UserCode"].ToString(), 
            Session["CoCode"].ToString(), "Invoice" }, Grv, new string[] { "cmdAdd", "cmdEdit", "cmdDelete" },
            new int[] { Grv.Columns.Count - 2, Grv.Columns.Count - 2 }, CommonModel.loginOut1);

        if (this.Page.Request.QueryString["InvoiceNo"] != null)
        {
            string invoiceNo = this.Page.Request.QueryString["InvoiceNo"].ToString();
            DataTable[] dt = comm.GetInvoiceContractFiles(invoiceNo);
            if (dt != null && dt.Length > 2)
            {
                if (dt[0] != null && dt[0].Rows.Count > 0)
                {
                    txtInvoiceNo.Text = dt[0].Rows[0]["InvoiceNo"].ToString();
                    txtInvoicAmount.Value = dt[0].Rows[0]["InvoiceAmount"].ToString();
                    txtDate.Value = dt[0].Rows[0]["InvoiceDate"].ToString();
                    TxtDesc.Text = dt[0].Rows[0]["InvoiceDesc"].ToString();
                    txtLeftAmount.Value = dt[0].Rows[0]["leftAmount"].ToString();
                }
                GrvFiles.DataSource = dt[1];
                GrvFiles.DataBind();
                Grv.DataSource = dt[2];
                Grv.DataBind();
            }

            if (txtLeftAmount.Value.Equals("0"))
            {
                this.lineFieldset.Visible = false;
                this.cmdDelete.Visible = false;
                this.cmdSure.Visible = false;
                Grv.Columns[Grv.Columns.Count - 2].Visible = false;
                Grv.Columns[Grv.Columns.Count - 1].Visible = false;
            }
        }
        else
        {
            ContractNoBind();
            GetTradingBillingAmount(ddlContractNo.SelectedValue.ToString(), "");
            HeadSet();
        }
    }
    
    public void ContractNoBind()
    {
        ddlContractNo.DataSource = comm.GetContractNo(Convert.ToInt16(ddlType.SelectedValue.ToString()));
        ddlContractNo.DataTextField = "ContractNoMain";
        ddlContractNo.DataValueField = "ContractNoMain";
        ddlContractNo.DataBind();
    }
    public void InvoiceHeadBind(string invoiceNo)
    {
        DataTable dt = comm.GetInvoiceHead(invoiceNo);
        if (dt != null && dt.Rows.Count > 0)
        {
            txtInvoiceNo.Text = dt.Rows[0]["InvoiceNo"].ToString();
            txtInvoicAmount.Value = dt.Rows[0]["InvoiceAmount"].ToString();
            txtDate.Value = dt.Rows[0]["InvoiceDate"].ToString();
            TxtDesc.Text = dt.Rows[0]["InvoiceDesc"].ToString();
            txtLeftAmount.Value = dt.Rows[0]["leftAmount"].ToString();
            txtExpressDeliveryNo.Text = dt.Rows[0][""].ToString();
            txtDespatchDate.Value = dt.Rows[0]["ExpressDeliveryNo"].ToString();
            txtSignInDate.Value = dt.Rows[0]["DespatchDate"].ToString();
            txtSignInDate.Value = dt.Rows[0]["SignInDate"].ToString();
        }
    }
    public void InvoiceContractBind(string invoiceNo)
    {
        Grv.DataSource = comm.GetInvoiceContract(invoiceNo);
        Grv.DataBind();
    }
    public void SoNoBind(string contractNo)
    {
        ddlSoNo.DataSource = comm.GetSoNo(contractNo);
        ddlSoNo.DataValueField = "TradingSoNo";
        ddlSoNo.DataTextField = "TradingSoNo";
        ddlSoNo.DataBind();        
    }
    private void HeadSet()
    {
        if (Grv.Rows.Count > 0)
        {
            txtInvoiceNo.Enabled = false;
            txtInvoicAmount.Disabled = true;
            txtDate.Disabled = true;
            txtExpressDeliveryNo.Enabled = false;
            txtSignInDate.Disabled = true;
            txtDespatchDate.Disabled = true;
        }
        else
        {
            txtInvoiceNo.Enabled = true;
            txtInvoicAmount.Disabled = false;
            txtDate.Disabled = false;
            txtExpressDeliveryNo.Enabled = true;
            txtSignInDate.Disabled = false;
            txtDespatchDate.Disabled = false;
        }
    }

    public void GetTradingBillingAmount(string contractNo, string soNo)
    {
        model.ContractNoMain = contractNo;
        model.SoNo = soNo;
        txtContractLeftAmount.Value = comm.GetTradingBillingAmount(model);
    }
    #endregion   
    
    protected void cmdSure_Click(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(txtInvoiceNo.Text))
        {
            CommonMethod.IsTimeOutUserCode(this, CommonModel.errorTimeOutUrl1);

            string filepath = FileUpload1.PostedFile.FileName;
            string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1);
            string lastname = filename.Substring(filename.LastIndexOf(".") + 1);

            string serverpath = CreateFile(txtInvoiceNo.Text);
            FileUpload1.PostedFile.SaveAs(Server.MapPath(serverpath + filename));

            model.UserCode = Session["UserCode"].ToString();
            model.date = System.DateTime.Now.ToString("yyyy-MM-dd hh:ss");
            model.InvoiceFileName = filename;
            model.InvoiceNo = txtInvoiceNo.Text;
            GrvFiles.DataSource = comm.InvoiceFilesAdd(model);
            GrvFiles.DataBind();
        }
        else { CommonMethod.regAlertMessage(updHead, "InvoiceNo can not null!", this); }
    }
    protected string CreateFile(string invoiceNo)
    {
        string serverpath = "~/InvoiceUploadFiles/" + invoiceNo + "/";
        string tempServerPath = Server.MapPath(serverpath);
        if (!Directory.Exists(tempServerPath))
        {
            DirectoryInfo folder = Directory.CreateDirectory(tempServerPath);
        }
        return serverpath;
    }
    public void GetFilesListShow(string invoiceNo)
    {
        string serverpath = "~/InvoiceUploadFiles/" + invoiceNo + "/";
        StringBuilder temp = new StringBuilder();
        try
        {
            DirectoryInfo Dir = new DirectoryInfo(Server.MapPath(serverpath));
            if (Dir.GetFiles().Length > 0)
            {
                int j = 1;
                temp.Append("<table border=\"1px\" cellpadding=\"0px\" style=\"table-layout:fixed;\" cellspacing=\"0px\"><thead>");
                temp.Append("<td style=\"width: 15px; text-algin:center;\"> NO</td>");
                temp.Append("<td style=\"width: 300px; text-algin:center;\"> File Name</td>");
                temp.Append("<td style=\"width: 150px; text-algin:left;\"> Download</td>");
                temp.Append("<td style=\"width: 150px; text-algin:left;\"> Delete</td></thead>");
                foreach (FileInfo fileName in Dir.GetFiles())
                {
                    temp.Append("<tr><td style=\"width: 200px; text-algin:center;\">" + j.ToString() + "</td>");
                    temp.Append("<td style=\"width: 300px; text-algin:center;\">" + fileName + "</td>");
                    temp.Append("<td style=\"width: 150px; text-algin:left;\"><a href='../FilesDownLoad.aspx?filePosition=InvoiceUploadFiles/"
                        + invoiceNo+"/" + fileName + "'>下载</a></td>");
                    temp.Append("<td style=\"width: 80px; text-algin:left; Cursor:hand\" onclick=\"fileDelete('InvoiceUploadFiles/"
                        + invoiceNo+ "/" + fileName + "')\">删除</td></tr>");
                }
                temp.Append("</table>");
            }
            else { temp.Append("No Files For this!"); }
        }
        catch
        {
            temp.Append("No Files For this!");
        }
    }
    protected void GrvFiles_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string invoiceFilesID = GrvFiles.DataKeys[e.RowIndex]["M_InvoiceFilesID"].ToString();
        DataTable dt = comm.InvoiceFilesDelete(invoiceFilesID);
        if (dt.Rows.Count < GrvFiles.Rows.Count)
        {
            string attachedFileName = GrvFiles.DataKeys[e.RowIndex]["filePath"].ToString();
            string path = Server.MapPath("~/InvoiceUploadFiles/" + attachedFileName);
            System.IO.FileInfo fiL = new System.IO.FileInfo(path);
            if (fiL.Exists)
            {
                fiL.Delete();
            }
            CommonMethod.regAlertMessage(updHead, "success！", this);
            GrvFiles.DataSource = dt;
            GrvFiles.DataBind();
        }
        else
        { CommonMethod.regAlertMessage(updHead, " failed！", this); }
    }
    protected void GrvFiles_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        ////鼠标经过事件
        //if (e.Row.RowIndex != -1)
        //{
        //    //设置悬浮鼠标指针形状为"小手"
        //    e.Row.Attributes["style"] = "Cursor:hand";
        //    if (e.Row.RowType == DataControlRowType.DataRow)
        //    {
        //        e.Row.Attributes.Add("onmouseover", "lastColor=this.style.backgroundColor;this.style.backgroundColor='#CCCC99';");
        //        e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=lastColor;");
        //        ((LinkButton)e.Row.Cells[GrvFiles.Columns.Count - 1].Controls[0]).Attributes.Add("onclick", "return confirm('确实要删除？');");
        //    }
        //}
    }
}
